#include "src/io/file.h"

#include <assert.h>


jellyfish::io::file::file() : file_(NULL),length_(0)
{

}

jellyfish::io::file::file( const char* file_path,const char* mode )
{
    open(file_path,mode);
}

jellyfish::io::file::~file()
{
	close();
}

bool jellyfish::io::file::open( const char* file_path,const char* mode )
{
	assert(NULL!=file_path);
	assert(NULL!=mode);
	if (NULL==file_path || NULL==mode)
	{
		return false;
	}

	close();

	file_ = fopen(file_path,mode);
	if (NULL==file_)
	{
		return false;
	}

	seek(0,SEEK_END);
	length_ = get_position();
	seek(0,SEEK_SET);

	return true;
}

void jellyfish::io::file::close()
{
	if (NULL!=file_)
	{
		fclose(file_);
		file_ = NULL;
	}
	length_ = 0;
}

uint64 jellyfish::io::file::seek( int64 offset, uint32 from )
{
	assert(NULL!=file_);
	return _fseeki64(file_,offset,from);
}

uint64 jellyfish::io::file::get_position() const
{
	assert(NULL!=file_);
	return _ftelli64(file_);
}

uint64 jellyfish::io::file::get_length() const
{
	return length_;
}

uint32 jellyfish::io::file::read( void* buf, uint32 count )
{
	assert(NULL!=file_);
	assert(count>0);
	assert(NULL!=buf);
	return fread(buf,1,count,file_);
}

uint32 jellyfish::io::file::write( const void* buf, uint32 count )
{
	assert(NULL!=file_);
	assert(count>0);
	assert(NULL!=buf);
	return fwrite(buf,1,count,file_);
}


